﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.ComponentModel;

namespace devtm.Editor.Configuration.formWpf
{
    public class DisplayTypeConstructor : TreeViewItem, INotifyPropertyChanged
    {


        public DisplayTypeConstructor(TypeContraint contrainte, Type type)
        {
            SelectedType = type;
            Contraint = contrainte;
            Header = "Undefine";

        }


        Type _SelectedType;
        public Type SelectedType
        {
            get { return _SelectedType; }
            set
            {

                if (value == null || _SelectedType == value)
                    return;

                _SelectedType = value;

                Header = _SelectedType.Name;

                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("SelectedType"));

                this.Items.Clear();

                if (!_SelectedType.ContainsGenericParameters)
                    return;

                foreach (Type i in _SelectedType.GetGenericArguments())
                    this.Items.Add(new DisplayTypeConstructor(new TypeContraint(i), null));

                this.ExpandSubtree();
            }
        }


        public TypeContraint Contraint { get; set; }
        public event PropertyChangedEventHandler PropertyChanged;


        /// <summary>
        /// Builds the new Type
        /// </summary>
        /// <returns></returns>
        public Type build()
        {

            if (_SelectedType == null)
                return null;

            if (!_SelectedType.IsGenericType)
                return _SelectedType;

            Type ret = _SelectedType;
            List<Type> t = new List<Type>();
            
            foreach (DisplayTypeConstructor ty in this.Items)
                
                if (ty.SelectedType != null)
                    t.Add(ty.build());
                
                

            if (t.Count > 0)
                return _SelectedType.MakeGenericType(t.ToArray());

            return _SelectedType;

        }

    }
}
